# coding: utf-8
import datetime

import httpx
import peewee
from apscheduler.schedulers.blocking import BlockingScheduler


BASE_URL = "http://221.231.104.6:18806"
DATABASE = peewee.MySQLDatabase("miaofu", user="mf", passwd="mf888888", host="127.0.0.1", port=3306)


class Device(peewee.Model):
    device_id = peewee.CharField(primary_key=True)
    device_name = peewee.CharField()
    device_code = peewee.CharField()
    data_time = peewee.DateTimeField()
    uptime = peewee.DateTimeField()
    is_use = peewee.IntegerField()
    total_rain_flow = peewee.CharField()
    rain_flow = peewee.CharField()
    water_level = peewee.CharField()
    up_water_level = peewee.CharField()
    low_water_level = peewee.CharField()

    class Meta:
        database = DATABASE
        table_name = "xl_device"


def load_site() -> dict:
    devices = httpx.get(BASE_URL + "/dbDevice/getList").json()["data"]
    site = {}
    for device in devices:
        if device["siteName"] is None:
            continue
        if device["siteName"] not in site:
            site[device["siteName"]] = device["siteCode"]
        elif site[device["siteName"]] != device["siteCode"]:
            print(f"Conflict: {site[device['siteName']]} != {device['siteCode']}")
    return site


def post_data():
    """
    upLevel 室外、闸外、下游、外河
    lowLevel 室内、闸内、上游、内河

    """
    site = load_site()
    data = []
    with DATABASE.connection_context():
        for item in Device.select().where(Device.is_use == 1):
            if item.device_name not in site:
                print(f"- [ERROR] {item.device_name} not found in site list.")
                continue
            data.append(
                {
                    "reportTime": item.data_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "readTime": item.data_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "rainData": item.rain_flow,
                    "waterData": item.water_level,
                    "upLevel": item.up_water_level,
                    "lowLevel": (
                        item.low_water_level
                        if item.device_name not in ["新建闸", "备用"]
                        else item.water_level
                    ),
                    "totalRainData": item.total_rain_flow,
                    "flowInfo": "N/A",
                    "voltage": "12.1",
                    "siteCode": site[item.device_name],
                }
            )
            print(
                f"- [{data[-1]['readTime']}] {item.device_name}({data[-1]['siteCode']}) | rainData: {data[-1]['rainData']} | waterData: {data[-1]['waterData']} | upLevel: {data[-1]['upLevel']} | lowLevel: {data[-1]['lowLevel']} | totalRainData: {data[-1]['totalRainData']}"
            )
    now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{now_str}] Found {len(data)} records.")
    try:
        response = httpx.post(BASE_URL + "/dbDeviceHistory/add", json=data, timeout=5)
    except Exception as e:
        response = str(e)
    print(f"[{now_str}] {response}")


if __name__ == "__main__":
    post_data()
    scheduler = BlockingScheduler()
    scheduler.add_job(post_data, "interval", minutes=5)
    scheduler.start()
